package com.mao.server.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mao.server.annotation.HoneyLogs;
import com.mao.server.constant.Constants;
import com.mao.server.constant.ResultConstant;
import com.mao.server.domain.enumuric.LogType;
import com.mao.server.domain.po.User;
import com.mao.server.exception.ServiceException;
import com.mao.server.service.UserService;
import com.mao.server.utils.BaseContext;
import com.mao.server.utils.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserService userService;

    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                               @RequestParam String username, @RequestParam String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(username), Constants.USERNAME, username);
        queryWrapper.like(StrUtil.isNotBlank(name), Constants.NAME, name);

        Page<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

    @HoneyLogs(operation = "用户", type = LogType.ADD)
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        try {
            user.setPassword(Constants.DEFAULT_PASSWORD);
            userService.save(user);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                throw new ServiceException(Constants.ACCOUNT_HAS_EXIST);
            } else {
                throw new ServiceException(ResultConstant.SYS_ERROR_MSG);
            }
        }
        return Result.success();
    }

    @HoneyLogs(operation = "用户", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        User currentUser = userService.getById(BaseContext.getCurrentId());
        if (id.equals(currentUser.getId())) {
            throw new ServiceException(Constants.CANNOT_DELETE_CURRENT_USER);
        } else {
            userService.removeById(id);
        }
        return Result.success();
    }

    @HoneyLogs(operation = "用户", type = LogType.UPDATE)
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateById(user);
        return Result.success();
    }

    @HoneyLogs(operation = "用户", type = LogType.BATCH_DELETE)
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        User currentUser = userService.getById(BaseContext.getCurrentId());
        if (currentUser != null && currentUser.getId() != null && ids.contains(currentUser.getId())) {
            throw new ServiceException(Constants.CANNOT_DELETE_CURRENT_USER);
        }
        userService.removeBatchByIds(ids);
        return Result.success();
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        User user = userService.getById(id);
        return Result.success(user);
    }

    @GetMapping("/selectAll")
    public Result selectAll() {
        return Result.success(userService.list());
    }


    /**
     * 批量导出
     *
     * @param username
     * @param name
     * @param ids
     * @param response
     * @throws IOException
     */
    @GetMapping("/export")
    public void exportData(@RequestParam(required = false) String username,
                           @RequestParam(required = false) String name,
                           @RequestParam(required = false) String ids,  //   1,2,3,4,5
                           HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);

        List<User> list;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // ["1", "2", "3"]   => [1,2,3]
        if (StrUtil.isNotBlank(ids)) {
            List<Integer> idsArr1 = Arrays.stream(ids.split(",")).map(Integer::valueOf).collect(Collectors.toList());
            queryWrapper.in("id", idsArr1);
        } else {
            // 第一种全部导出或者条件导出
            queryWrapper.like(StrUtil.isNotBlank(username), "username", username);
            queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        }
        // 查询出当前User表的所有数据
        list = userService.list(queryWrapper);
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户信息表", "UTF-8") + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream, true);
        writer.close();
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 批量导入
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    public Result importData(MultipartFile file) throws IOException {

        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<User> userList = reader.readAll(User.class);

        try {
            // 写入数据到数据库
            userService.saveBatch(userList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("数据批量导入错误");
        }
        return Result.success();
    }

}
